<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class GacSach extends CI_Controller {
	
	private $cipher;
	
	function __construct() {
		parent::__construct();
		$this->load->helper('aescipher');
		$this->cipher = new AESCipher();
	}
	
	function categories() {
		$this->load->model('gacsachmodel');
		$categories = $this->gacsachmodel->get_categories();
		echo $this->cipher->encrypt(json_encode($categories));
	}
	
	function top_stories($page, $page_num=20) {
		$page = (int) $page;
		if ($page < 1 || $page > 10) $page = 1;
		if ($page_num < 1 || $page_num > 50) $page_num = 15;
		$page_num = (int) $page_num;
		$this->load->model('gacsachmodel');
		$stories = $this->gacsachmodel->get_top_stories($page, $page_num);
		echo $this->cipher->encrypt(json_encode($stories));
	}
	
	function stories($tag, $page, $page_num=15, $order_column_name='view_count', $order_value='desc') {
		$page = (int) $page;
		if ($page_num < 1 || $page_num > 50) $page_num = 15;
		$page_num = (int) $page_num;
		$tag = strip_quotes($tag);
		$this->load->model('gacsachmodel');
		$data = $this->gacsachmodel->get_stories($tag, $page, $page_num, $order_column_name, $order_value);
		echo $this->cipher->encrypt(json_encode($data));
	}
	
	function detail($id, $chap_index) {
		$this->load->model('gacsachmodel');
		$story = $this->gacsachmodel->get_story($id);
		$DATA_PATH = '/home/longhoanggiang/data/gacsach/'.$id.'/'.$chap_index.'.chap';
		ob_start();
		readgzfile($DATA_PATH);
		$content = ob_get_clean();
		$content = nl2br($content);
		$data = new stdClass();
		$data->title = "Gác Sách - ".$story->name;
		$data->story = $story;
		$data->content = $content;
		$this->load->view('detail_view', $data);
	}
	
}
